/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package network;

import java.util.ArrayList;
import java.util.Collection;
import schedulingScheme.*;
import java.util.List;

/**
 *
 * @author Andrzej
 */
public class NetworkController implements NetworkListener{
    private List<SensorNode> sensors;
    private List<POI> pois;
    private Network network;
    private SensorsController algorithm;
    private Collection<EventListener> eventListeners = new ArrayList<EventListener>();

    public NetworkController(List<SensorNode> sensors, List<POI> pois, Network network, SensorsController algorithm) {
        this.sensors = sensors;
        this.pois = pois;
        this.network = network;
        this.algorithm = algorithm;
    }

    public void start(){
        SensorNode sink = new SensorNode(0, 0, 0, Double.MAX_VALUE);
        sink.setOn(true);
        network.addSink(sink);
        List<SensorNode> toBeActivated = algorithm.initializeNodes();
        for (SensorNode s: toBeActivated){
            s.setOn(true);
            network.addSensor(s);
        }
        network.addNetworkListener(this);
        network.start();
    }



    @Override
    public void sensorDied(SensorNode s, int time) {
        List<SensorNode> nodesToAdd = algorithm.replaceDiedSensor(s);
        for (SensorNode node: nodesToAdd){
            node.setOn(true);
            network.addSensor(node);
        }
        for (EventListener el: eventListeners){
            el.diedSensorActionPerformed(s, nodesToAdd, time);
        }
    }

    public void addEventListener(EventListener el){
        eventListeners.add(el);

    }


    public boolean newRound(int roundNumber, int time) {
        
        //Bio will be called here
        List<SensorNode> res = algorithm.roundPassed(roundNumber);
        if (res == null)
            return false;
        for (SensorNode s: sensors){
            s.setOn(false);
            network.removeSensor(s);
        }
        for (SensorNode s : res) {
            if (s.getBattery() > 0) {
                s.setOn(true);
                network.addSensor(s);
            }
        }
        for (EventListener el : eventListeners) {
            el.networkReorganizedPerformed(time);
        }

        return true;
    }

    public void timePassed(int time) {
        if (algorithm.reactToTimePassed(time)) {
            for (EventListener el : eventListeners) {
                el.networkReorganizedPerformed(time);
            }

        }
    }

    public void networkReorganized(int roundNumber, int time) {
        for (EventListener el : eventListeners) {
            el.networkReorganizedPerformed(roundNumber, time);
        }
    }



}
